import React, { Component } from 'react'
import { router, Redirect } from 'umi'
import { connect } from 'dva'
import { Spin } from 'antd'
import { findFatherTree } from '@u/utils-cjy'

@connect((s) => ({
  ...s['login'],
  ...s['menuList'],
  loading: s.loading.models['login'],
}))
class Authorize extends Component {
  componentDidMount() {
    const { isLogin, location, dispatch } = this.props
    if (isLogin) {
      dispatch({
        type: 'login/getUserInfo',
      })
    } else {
      router.push({
        pathname: '/login',
        state: { from: location },
      })
    }
  }

  renderSpin = () => {
    return (
      <div style={{ textAlign: 'center', paddingTop: '15%' }}>
        <Spin size={'large'}/>
      </div>
    )
  }
  renderChild = () => {
    const { children, location, menuList } = this.props
    const { pathname } = location
    const authArr = findFatherTree(menuList, pathname)
    // console.log(authArr)
    return (
      authArr.length
        ? children
        : <Redirect to={'/403'}/>
    )
  }

  render() {
    const { loading } = this.props
    return (
      (loading || loading === undefined)
        ? this.renderSpin()
        : this.renderChild()
    )
  }
}

export default Authorize
